package cn.iocoder.yudao.module.system.framework.translate.core.impl;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.system.framework.translate.config.TranslateConfig;
import cn.iocoder.yudao.module.system.framework.translate.core.ITranslateClient;
import org.apache.http.HttpHost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * Description: 谷歌翻译（免费版）实现
 * Author: li
 * Date: 2024/2/20
 */
@Component
public class GoogleFreeTranslateClientImpl implements ITranslateClient {
    @Resource
    private TranslateConfig translateConfig;
    private CloseableHttpClient httpclient;

    @PostConstruct
    public void initHttpClient() {
        final String proxyHost = translateConfig.getProxyHost();
        final Integer proxyPort = translateConfig.getProxyPort();
        if (StrUtil.isNotEmpty(proxyHost) && proxyPort != null) {
            // 使用代理访问
            this.httpclient = HttpClients.custom().setProxy(new HttpHost(proxyHost, proxyPort)).build();
        } else {
            this.httpclient = HttpClients.createDefault();
        }
    }

    @Override
    public String translate(String text, String targetLanguage) {
        final String translateText = GoogleFreeTranslateUtil.translateText(httpclient, text, "auto", targetLanguage);
        return translateText;
    }

}
